<?php
/**
 * Created by PhpStorm.
 * User: bob
 * Date: 2021/4/27
 * Time: 9:20
 */

namespace App\Api\Auth\Services;


use App\Api\Auth\Models\Functions;
use App\Api\Auth\Models\PermissionFunction;
use App\Api\Auth\Models\Permissions;
use App\Api\Auth\Models\PermissionUser;
use App\Api\Auth\Models\Users;
use App\Api\Auth\Services\AuthService;
use App\User;
use \Auth;
use Complex\Exception;

class UserService
{
    /**添加店铺专用
     * @param $params
     * @return Users
     */
    static function userAdd($params)
    {
        $supplier_id          = array_pull($params, 'supplier_id');
        $params['password']   = bcrypt($params['password']);
        $params['api_token']  = str_random(50);
        $params['created_at'] = date('Y-m-d H:i:s');
        $params['updated_at'] = date('Y-m-d H:i:s');
        $secret               = str_random(10);
        \DB::beginTransaction();
        try {
            $user_id = User::insertGetId($params);
            $res     = Users::create(
                ['user_id' => $user_id, 'shop_id' => $user_id, 'secret' => $secret]);
            if ($supplier_id) {
                UserUser::firstOrCreate(['shop_id' => $supplier_id, 'child_shop_id' => $user_id]);
                //自动关联上游所有人可见的产品  然后使用默认佣金
                $orderPages = \DB::table('plan_order_pages as op')
                    ->leftjoin('plan_order_pages_user as opu', function ($join) use ($user_id) {
                        $join->on('opu.order_page_id', '=', 'op.id')
                            ->where('opu.child_shop_id', '=', $user_id);
                    })
                    ->where('opu.id', '=', null)
                    ->where('op.shop_id', '=', $supplier_id)
                    ->select('op.id', 'op.visible')
                    ->get();

                foreach ($orderPages as $orderPage) {
                    $orderPageId = data_get($orderPage, 'id');
                    $visible     = data_get($orderPage, 'visible');
                    $status      = 100;
                    if ($visible == 2 || $visible == 4) {
                        $status = 200;
                    }
                    PlanOrderPageUser::create([
                        'order_page_id' => $orderPageId,
                        'child_shop_id' => $user_id,
                        'commission'    => -1,
                        'status'        => $status,
                    ]);
                }
//                $order_pages = PlanOrderPages::select('id', 'commission')->where('shop_id', $supplier_id)
//                    ->where('visible', 2)->get();
//                foreach ($order_pages as $order_page) {
//                    PlanOrderPageUser::firstOrCreate([
//                        'order_page_id' => data_get($order_page, 'id', 0),
//                        'child_shop_id' => $user_id,
//                        'commission'    => data_get($order_page, 'commission', 0),
//                        'status'        => 200,
//                    ]);
//                }
            }
            addAdminLogs([
                'table_name' => 'users',
                'log_info'   => '新增91店铺',
                'remark'     => serialize($params)
            ]);
            $user = User::where('id', $user_id)->first();
            Auth::login($user);
            Permissions::create([
                'shop_id'   => $user_id,
                'name'      => data_get($params, 'name', ''),
                'parent_id' => 0,
                'level'     => 1
            ]);
            //权限初始化
            $shop_id = $user_id;
            if (!$shop_id) throw new \LogicException('未获取到系统id');
            $permission_id = Permissions::where('shop_id', $shop_id)->where('parent_id', 0)->value('id');
            if (PermissionFunction::where('permission_id', $permission_id)->value('permission_id'))
                throw new \LogicException('系统已初始化，请联系管理员');
            $functions = Functions::where('code', '!=', '074')->where('created_at', '>', '2019-08-01')->pluck('id');//pluck
            $datas     = [];
            foreach ($functions as $key => $function) {
                $datas[$key] = [
                    'permission_id' => $permission_id,
                    'func_id'       => $function,
                ];
            }//dd($datas);
            $res = \DB::table('permission_func')->insert($datas);
            PermissionUser::firstOrCreate(['user_id' => $shop_id, 'permission_id' => $permission_id]);

            $permission_id     = PermissionUser::where('user_id', data_get($user, 'id', 0))->value('permission_id');
            $user['functions'] = PermissionFunction::where('permission_id', $permission_id)->get();
            if (!empty($user['functions'])) foreach ($user['functions'] as $key => $function) {
                $function_id             = $function['func_id'];
                $func                    = Functions::where('id', $function_id)->first();
                $user['functions'][$key] = $func;
                //$user = AuthService::getUserRole($user);
            }
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            ding('error.wq', '店铺注册报错' . $e->getMessage());
            throw new \LogicException('系统繁忙请稍后重试');
        }
        return $user;
    }

    /**店铺登录
     * @param $params
     * @param $ip
     * @return User|array
     */
    static function userLogin($params,$ip='')
    {
        $remember = data_get($params, 'remember', 0);
        if ($remember) {
            $remember = true;
        } else {
            $remember = false;
        }
        if (!empty($params['name'])) {
            $res = User::where('name', '=', $params['name'])->value('status');
            if (empty($res)) {
                $res = User::where('mobile', '=', $params['name'])->value('status');
            }
            if ($res == config('auth.status.stop_use')) {
                throw new \LogicException('账号已停用', 300);
            }
            if ($res == config('auth.status.deleted')) {
                throw new \LogicException('账号不存在', 400);
            }
        } else {
            throw new \LogicException('用户名或密码错误', 20);
        }
        if (Auth::attempt(['name' => $params['name'], 'password' => $params['password']], $remember) or Auth::attempt(['mobile' => $params['name'], 'password' => $params['password']], $remember)) {
            $user              = AuthService::getUserRole(Auth::user());
            $permission_id     = PermissionUser::where('user_id', data_get($user, 'id', 0))->value('permission_id');
            $user['functions'] = PermissionFunction::where('permission_id', $permission_id)->get();
            if (!empty($user['functions'])) foreach ($user['functions'] as $key => $function) {
                $function_id             = $function['func_id'];
                $func                    = Functions::where('id', $function_id)->first();
                $user['functions'][$key] = $func;
            }
            $shop_id = UserService::getShopId($user);
            info('91登录信息店铺id用户名',[$shop_id,data_get($user,'name'),$ip]);
            return $user;
        } else {
            throw new \LogicException('用户名或密码错误', 20);
        }

    }

    /**上游列表
     * @param $params
     * @return mixed
     */
    static function supplierList($params)
    {
        $page     = data_get($params, 'page', 1);
        $pageSize = data_get($params, 'page_size', 20);
        $user     = authUser();
        $shop_id  = UserService::getShopId($user);
        $list     = UserUser::select('shop_id', 'u.name', 'u.mobile')->where('child_shop_id', $shop_id)
            ->join('users as u', 'u.id', '=', '91_user_user.shop_id')
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();
        return $list;
    }

    static function supplierSearch($params)
    {
        $secret      = data_get($params, 'secret', '');
        $supplier_id = Users::where('secret', $secret)->value('user_id');
        if (!$supplier_id) throw new \LogicException('秘钥不正确', 55);
        $name = User::where('id', $supplier_id)->value('name');
        return $name;
    }

    /**添加上游
     * @param $params
     * @return mixed
     */
    static function supplierAdd($params)
    {
        $secret      = data_get($params, 'secret', '');
        $supplier_id = Users::where('secret', $secret)->value('user_id');
        if (!$supplier_id) throw new \LogicException('秘钥不正确', 55);
        $user    = authUser();
        $shop_id = UserService::getShopId($user);
        if (UserUser::where(['shop_id' => $supplier_id, 'child_shop_id' => $shop_id])->first())
            throw new \LogicException('不可重复添加供应商!');
        $res = UserUser::Create(['shop_id' => $supplier_id, 'child_shop_id' => $shop_id]);
        //自动关联上游所有人可见的产品  然后使用默认佣金

        $orderPages = \DB::table('plan_order_pages as op')
            ->leftjoin('plan_order_pages_user as opu', function ($join) use ($shop_id) {
                $join->on('opu.order_page_id', '=', 'op.id')
                    ->where('opu.child_shop_id', '=', $shop_id);
            })
            ->where('opu.id', '=', null)
            ->where('op.shop_id', '=', $supplier_id)
            ->select('op.id', 'op.visible')
            ->get();

        foreach ($orderPages as $orderPage) {
            $orderPageId = data_get($orderPage, 'id');
            $visible     = data_get($orderPage, 'visible');
            $status      = 100;
            if ($visible == 2 || $visible == 4) {
                $status = 200;
            }
            PlanOrderPageUser::create([
                'order_page_id' => $orderPageId,
                'child_shop_id' => $shop_id,
                'commission'    => -1,
                'status'        => $status,
            ]);
        }
        return $res;
    }

    /**上游产品
     * @param $params
     * @return mixed
     */
    static function getSupplierProducts($params)
    {
        $page        = data_get($params, 'page', 1);
        $pageSize    = data_get($params, 'page_size', 20);
        $shopId      = data_get($params, 'shop_id', '');//哪个上游
        $parent_name = data_get($params, 'parent_name', '');
        $title       = data_get($params, 'title', '');
        $user        = authUser();
        $shop_id     = UserService::getShopId($user);
        $products    = PlanOrderPageUser::where('child_shop_id', $shop_id)
            ->join('plan_order_pages as pop', 'pop.id', '=', 'plan_order_pages_user.order_page_id')
            ->join('users as u', 'u.id', '=', 'pop.shop_id')
            ->leftjoin('plan_order_pages as child_pop', function ($join) use ($shop_id) {
                $join->on('child_pop.parent_id', '=', 'pop.id')
                    ->where('child_pop.shop_id', '=', $shop_id);
            })->leftjoin('commission_page_configs as dpc',function ($join){
                $join->on('dpc.page_id','=','pop.id')
                    ->where('dpc.type','=',1);
            })->leftjoin('commission_page_configs as spc','spc.id','=','plan_order_pages_user.config_id')
            //->distinct('pop.id')//\DB::raw('distinct pop.id'),
            ->select('pop.id', 'pop.title','pop.tika_cost', 'pop.selling_point', 'pop.commission as commission2', 'pop.image1', 'pop.product_id', 'pop.created_at',
                \DB::raw('if(plan_order_pages_user.config_id=0,dpc.active_commission,spc.active_commission) as active_commission'),
                \DB::raw('if(plan_order_pages_user.config_id=0,dpc.id,spc.id) as page_id'),
                \DB::raw('if(plan_order_pages_user.config_id=0,dpc.first_recharge_one,spc.first_recharge_one) as first_recharge_one'),
                \DB::raw('if(plan_order_pages_user.config_id=0,dpc.first_recharge_one_commission,spc.first_recharge_one_commission) as first_recharge_one_commission'),
                \DB::raw('if(plan_order_pages_user.config_id=0,dpc.first_recharge_two,spc.first_recharge_two) as first_recharge_two'),
                \DB::raw('if(plan_order_pages_user.config_id=0,dpc.first_recharge_two_commission,spc.first_recharge_two_commission) as first_recharge_two_commission'),
                \DB::raw('if(plan_order_pages_user.config_id=0,dpc.recharge_amount_two,spc.recharge_amount_two) as recharge_amount_two'),
                \DB::raw('if(plan_order_pages_user.config_id=0,dpc.recharge_amount_two_commission,spc.recharge_amount_two_commission) as recharge_amount_two_commission'),
                \DB::raw('if(plan_order_pages_user.config_id=0,dpc.recharge_amount_one_commission,spc.recharge_amount_one_commission) as recharge_amount_one_commission'),
                \DB::raw('if(plan_order_pages_user.config_id=0,dpc.recharge_amount_one,spc.recharge_amount_one) as recharge_amount_one'),
                \DB::raw('if(plan_order_pages_user.config_id=0,dpc.rules,spc.rules) as rules'),
                'pop.commission_rule', 'plan_order_pages_user.commission', 'u.name as parent_name', 'pop.fetch_code', 'pop.image1', 'child_pop.id as added')//child_pop.id这个前端判断是否添加过
                ->where('plan_order_pages_user.status', '=', 200)
            ->where('pop.status', '=', 100)->groupby('pop.id');
        $shopId ? $products->where('pop.shop_id', '=', $shopId) : '';
        $parent_name ? $products->where('u.name', 'like', '%' . $parent_name . '%') : '';
        $title ? $products->where('pop.title', 'like', '%' . $title . '%') : '';
        $products = $products->orderby('pop.id','desc')
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();
        if (is_array(data_get($products, 'data', [])) && !empty(data_get($products, 'data', [])))
            foreach (data_get($products, 'data', []) as $key => $value) {
                if (data_get($value, 'commission') < 0) {
                    $products['data'][$key]['commission'] = data_get($value, 'commission2', 0);
                }
                $products['data'][$key]['commission']    = round($products['data'][$key]['commission'], 2);
                $products['data'][$key]['selling_point'] = json_decode(data_get($value, 'selling_point'), '');
            }

        return $products;
    }

    /**获取某分销商继承我的产品
     * @param $params
     * @return mixed
     */
    static function getMerchantProducts($params)
    {
        $page        = data_get($params, 'page', 1);
        $pageSize    = data_get($params, 'page_size', 20);
        $merchant_id = data_get($params, 'merchant_id');
        if (!$merchant_id) throw new \LogicException('缺少必要参数！！！');
        $user     = authUser();
        $shop_id  = UserService::getShopId($user);
        $products = \DB::table('plan_order_pages as page')
            ->select('page.title', 'page.fetch_code', 'page.shop_id as my_page_id', 'p.shop_id as product_shop_id',
                'p.name as product_name', 'parent_p.title as parent_title', 'page.created_at', 'page.id')
            ->where('page.shop_id', $shop_id)
            ->join('plan_order_pages as child_p', function ($join) use ($merchant_id) {
                $join->on('child_p.parent_id', '=', 'page.id')
                    ->where('child_p.shop_id', '=', $merchant_id);
            })->leftJoin('plan_products as p', 'p.id', '=', 'page.product_id')
            ->leftJoin('plan_order_pages as parent_p', 'parent_p.id', '=', 'page.parent_id')
            ->where('child_p.status', 100)//1.7只读取下游上架的商品
            ->groupBy('page.id')//我一个商品被下游继承多次的场景
            ->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();
        return $products;
    }

    /**下游列表
     * @param $params
     * @return mixed
     */
    static function partnerList($params)
    {
        $name     = data_get($params, 'name', '');
        $cm_id    = data_get($params, 'cm_id', '');
        $page     = data_get($params, 'page', 1);
        $selling     = data_get($params, 'selling', 0);
        $pageSize = data_get($params, 'page_size', 20);
        $user     = authUser();
        $shop_id  = UserService::getShopId($user);
        $user_ids = [];
        if ($selling){
            $user_ids = \DB::select ("SELECT shop_id from plan_order_pages where parent_id in (SELECT id from plan_order_pages where shop_id = {$shop_id} and `status` = 100)  and `status` = 100 GROUP BY shop_id");
            if (!empty($user_ids)) $user_ids = collect($user_ids)->pluck('shop_id');
        }
        $query    = UserUser::select('91_user_user.nick_name','91_user_user.id','shop_id', 'u.name','u.com','u.real_name', 'u.mobile', 'u.address', 'child_shop_id', 'cm_id', 'u.created_at', 'cm.name as cm_name')
            ->where('shop_id', $shop_id)
            ->join('users as u', 'u.id', '=', '91_user_user.child_shop_id')
            ->leftjoin('users as cm', 'cm.id', '=', '91_user_user.cm_id');
        if ($user->id == $shop_id) $query->addselect('91_user_user.mobile as m_mobile','91_user_user.company as m_company','partner');
        if ($name) $query->where('u.name', 'like', '%' . $name . '%');
        if ($cm_id) $query->where('cm_id', '=', $cm_id);
        if (!empty($user_ids)) $query->wherein('u.id', $user_ids);
        $list = $query->paginate($pageSize, ['*'], 'page', $page)
            ->toArray();
        return $list;
    }

    /**下游订单
     * @param $params
     * @return mixed
     */
    static function partnerOrders($params)
    {
        $user    = authUser();
        $shop_id = UserService::getShopId($user);
        $orders  = PlanCommission::where('parent_id', $shop_id)
            ->join('plan_orders as o', 'o.id', '=', 'plan_commissions.order_id')->get();
        return $orders;
    }

    /**编辑佣金
     * @param $params
     * @return mixed
     */
    static function partnerCommission($params)
    {
        $user          = authUser();
        $shop_id       = UserService::getShopId($user);
        $order_page_id = data_get($params, 'order_page_id', 0);
        $page          = PlanOrderPages::where('shop_id', $shop_id)->where('id', $order_page_id)->count();
        if (!$page > 0) throw new \LogicException('销售页店铺关联出错', 66);
        $child_shop_id = data_get($params, 'child_shop_id', 0);
        $commission    = data_get($params, 'commission', 0);
        $res           = PlanOrderPageUser::where('order_page_id', $order_page_id)->where('child_shop_id', $child_shop_id)
            ->update(['commission' => $commission]);
        return $res;
    }

    /**
     * 获取商铺id
     * @param $user
     * @return mixed
     */
    public static function getShopId($user)
    {
        $shopId = Users::where('user_id', '=', data_get($user,'id',0))
            ->value('shop_id');
        //$shopId    = data_get($userExtra, 'shop_id', '');
        if (empty($shopId)) {
            throw new \LogicException('未找到该用户对应的店铺信息', 400);
        }
        return $shopId;
    }

    /**
     * 是不是他的子类
     * @param $shopId
     * @param $childShopId
     * @return bool
     */
    public static function isChildShop($shopId, $childShopId)
    {
        $isRepeat = UserUser::where('shop_id', '=', $shopId)
            ->where('child_shop_id', '=', $childShopId)
            ->first();

        if (empty($isRepeat) || is_null($isRepeat)) {
            return false;
        }

        return true;
    }

    /**
     * 根据店铺id获取下级id
     * @param $shopId
     * @return mixed
     */
    public static function getChildByShopId($shopId)
    {
        $childUsers = UserUser::where('shop_id', '=', $shopId)
            ->pluck('child_shop_id')
            ->toArray();
        return $childUsers;
    }

    static function userExist($shop_id, $user_id)
    {
        $user = Users::where(['shop_id' => $shop_id, 'user_id' => $user_id])->first();
        return $user;
    }

    /**员工列表
     * @param $params
     * @return mixed
     */
    public static function userList($params)
    {
        $user      = authUser();
        $shopId    = UserService::getShopId($user);
        $page      = $params['page'];
        $pageSize  = $params['page_size'];
        $real_name = data_get($params, 'real_name', '');
        //$sql       = User::select('users.name as name', 'users.real_name', 'users.status', 'users.id');
        $sql = User::select('users.name as name', 'users.real_name', 'users.status', 'users.id', 'p2.name as dept', 'p1.name as job')
            ->join('91_users as no', 'no.user_id', '=', 'users.id')
            ->leftjoin('permission_user as pu', 'pu.user_id', '=', 'users.id')
            ->leftjoin('permissions as p1', 'pu.permission_id', '=', 'p1.id')//岗位
            ->leftjoin('permissions as p2', 'p2.id', '=', 'p1.parent_id');//部门
        //->join('permissions as p3', 'p3.id', '=', 'p2.parent_id');//系统
        if ($real_name) $sql = $sql->where('real_name', 'like', '%' . $real_name . '%');
        $users = $sql->where('no.shop_id', $shopId)->where('no.user_id', '!=', $shopId)->paginate($pageSize, ['*'], 'page', $page)->toArray();
        //$users = $sql->paginate($pageSize, ['*'], 'page', $page)->toArray();
        //$users = $users??[1];
        $data = data_get($users, 'data', []);
        if (!empty($data)) foreach ($data as $key => $user) {
            if ($user['status'] == 0) $data[$key]['status'] = '在用';
            if ($user['status'] == 10) $data[$key]['status'] = '停用';
            if ($user['status'] == -1) $data[$key]['status'] = '隐刀';
        }
        $users['data'] = $data;
        return $users;
    }

    static function outerStoreIsValid($id, $cookie)
    {
        try {
            $outer_store = OuterStores::find($id);
            $shopSource  = data_get($outer_store, 'source');
            $storeName   = data_get($outer_store, 'shop_name', '');
            switch ($shopSource) {
                case 'tmall':
//                    $c = new TmallClient($storeName);
                    return true;
                    break;
                case 'jd':
                    $c   = new JdClient($storeName);
                    $res = $c->fetchShopInfo($cookie);
                    $j   = json_decode($res, 1);
                    info('京东验证cookie有效', [$id, $cookie, $j]);
                    $shopName = data_get($j, 'shopName', '');
                    if (strpos($res, '账户登录') !== false)
                        throw new \LogicException('cookie无效', 200);
                    if ($shopName != $storeName) {
                        throw new \LogicException('cookie和店铺不一致，请登录店铺，重新获取cookie');
                    }
                    return true;
                    break;
                case 'pdd':
                    $c   = new PddWebClient($storeName);
                    $res = $c->fetchShopInfo($cookie);
                    info('拼多多验证cookie有效', [$id, $cookie, $res]);
                    if (strpos($res, '会话已过期') !== false) {
                        throw new \LogicException('cookie无效', 200);
                    }
                    $j        = json_decode($res, 1);
                    $shopName = data_get($j, 'result.mallName', '');
                    if ($shopName != $storeName) {
                        throw new \LogicException('cookie和店铺不一致，请登录店铺，重新获取cookie');
                    }
                    return true;
                    break;
//            case 'youzan':
//                OrderService::deliveryOrder($shopSource, $storeName);
//                break;
                default:
                    throw new \LogicException('店铺配置错误');
            }
        } catch (\Exception $e) {
            info('店铺cookie认证失败' . $e->getMessage());
            throw new \LogicException('登录失败');
        }
    }

    static function getGroup($shop_id, $parent_id, $count = 1)
    {
        $group = Permissions::where('shop_id', $shop_id)->where('parent_id', $parent_id)->get();
        if (empty($group)) return [];
        if ($count <= 0) return $group;
        $count--;
        foreach ($group as $key => $first_level) {
            $parent_id = data_get($first_level, 'id');
            $child = static::getGroup($shop_id,$parent_id,$count);
            data_set($group, $key . '.child',$child);
            }
        return $group;
    }

    static function newSerect(){
        $new_secret = str_random(10);
        $exist = Users::where('secret', $new_secret)->first();
        if (!$exist) return $new_secret;
        return static::newSerect();
    }
}